package me.mingshan.leetcode;

/**
 * @author hanjuntao
 * @date 2025/6/10 0010
 */
public class L_917_reverse_only_letters {
    public static void main(String[] args) {
        String s = "a-bC-dEf-ghIj";
        System.out.println(reverseOnlyLetters(s));
    }

    /**
     * 输入：s = "a-bC-dEf-ghIj"
     * 输出："j-Ih-gfE-dCba"
     *
     * 在交换时，碰到非字母，跳过，直到遇到字母，交换，然后继续交换，直到结束。
     *
     * @param s
     * @return
     */
    public static String reverseOnlyLetters(String s) {
        int left = 0;
        int right = s.length() - 1;

        char[] chars = s.toCharArray();
        while (left < right) {
            if (!Character.isLetter(chars[left])) {
                left++;
            } else if (!Character.isLetter(chars[right])) {
                right--;
            } else {
                char temp = chars[left];
                chars[left] = chars[right];
                chars[right] = temp;
                left++;
                right--;
            }
        }

        return new String(chars);
    }
}
